﻿using DevelopTool.Bll.DbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.LodingForm;
using DevelopTool.Model.CommonModels;
using DevelopTool.Model.DbModels;
using DevelopTool.Model.Enums;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DevelopTool.Forms.CommonControls
{
    /// <summary>
    /// 数据库连接选择控件
    /// </summary>
    public partial class DbinfoComboBox : UIUserControl
    {
        #region 私有属性

        /// <summary>
        /// 顶级节点
        /// </summary>
        private TreeNode topNode;

        #endregion 私有属性


        #region 公有属性

        /// <summary>
        /// 数据库连接信息集合
        /// </summary>
        private List<ManageMenu> manageMenus;
        public List<ManageMenu> ManageMenus
        {
            get
            {
                return manageMenus;
            }
            set
            {
                manageMenus = value;
            }
        }

        private DbInfo defaultSelectedDbInfo;
        /// <summary>
        /// 默认选择的数据库连接
        /// </summary>
        public DbInfo DefaultSelectedDbInfo
        {
            get
            {
                return defaultSelectedDbInfo;
            }
            set
            {
                defaultSelectedDbInfo = value;
                selectedDbInfo = value;

                //绑定默认的菜单选择项
                if (this.defaultSelectedDbInfo != null)
                    this.cboTreeDbInfo.SelectedNode = TreeViewHelper.FindNode(topNode, manageMenus.FirstOrDefault(it => it.Id == this.defaultSelectedDbInfo.Id));
            }
        }


        private DbInfo selectedDbInfo;
        /// <summary>
        /// 默认选择的数据库连接
        /// </summary>
        public DbInfo SelectedDbInfo
        {
            get
            {
                return selectedDbInfo;
            }
        }

        #endregion 公有属性

        #region 事件
        //事件参数
        public delegate void OperationHandler(object sender, DbinfoEventArgs e);

        /// <summary>
        /// 数据库连接选择事件
        /// </summary>
        [Description("数据库选择事件"), Category("DevelopTool")]
        public event OperationHandler DbInfoSelected;
        #endregion 事件


        public DbinfoComboBox()
        {
            InitializeComponent();
        }


        private void DbinfoSelectCombo_Load(object sender, EventArgs e)
        {
            try
            {
                this.cboTreeDbInfo.TreeView.Font= new Font("宋体", 10F);

                TreeNode notNode = new TreeNode("无")
                {
                    Name = "notNode",
                    Tag = new ManageMenu() { Id = 0, NodeType = MenuNodeType.Node }
                };
                this.cboTreeDbInfo.Nodes.Add(notNode);

                this.topNode = new TreeNode("数据库列表")
                {
                    Name = "TopNode",
                    Tag = new ManageMenu() { Id = 0, NodeType = MenuNodeType.Folder }
                };
                this.cboTreeDbInfo.Nodes.Add(topNode);
                this.manageMenus = new DbInfoBll().GetList().Cast<ManageMenu>().ToList();
                this.BindCboTreeViewData(topNode, this.manageMenus, 0);
                topNode.Expand();//展开外层节点
            }
            catch
            {}
        }


        /// <summary>
        /// 绑定下拉框数据
        /// </summary>
        /// <param name="parNode"></param>
        /// <param name="list"></param>
        /// <param name="nodeId"></param>
        private void BindCboTreeViewData(TreeNode parNode, List<ManageMenu> list, int nodeId)
        {
            var childNodeList = list.FindAll(t => t.NodePid == nodeId);
            foreach (var childNode in childNodeList)
            {
                var node = new TreeNode
                {
                    Name = childNode.Id.ToString(),
                    Text = childNode.NodeName,
                    Tag = childNode
                };
                parNode.Nodes.Add(node);
                BindCboTreeViewData(node, list, childNode.Id);
            }
        }

        /// <summary>
        /// 数据库连接选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="node"></param>
        private void cboTreeDbInfo_NodeSelected(object sender, TreeNode node)
        {
            if (!(node.Tag is ManageMenu manageMenu)) return;

            if (!(manageMenu is DbInfo dbInfo) || dbInfo.Id <= 0)
            {
                this.cboTreeDbInfo.SelectedNode = null;
                this.selectedDbInfo = null;
                DbInfoSelected?.Invoke(sender, new DbinfoEventArgs() { DbInfo = null, IsConnect = false });//触发选择事件
            }
            else
            {
                //尝试连接数据库
                bool connectResult = false;

                LoadingHelper.ShowLoading("尝试连接数据库", () =>
                {
                    connectResult = new DbManagerBll(dbInfo).CheckDbConnect();
                });

                if (!connectResult)
                {
                    UINotifierHelper.ShowNotifier($"【{dbInfo.NodeName}】连接失败！", UINotifierType.ERROR, UIStyles.CurrentResources.ErrorTitle, true, 10000);
                    this.cboTreeDbInfo.SelectedNode = null;
                    dbInfo = null;
                }
                this.selectedDbInfo = dbInfo;
                DbInfoSelected?.Invoke(sender, new DbinfoEventArgs() { DbInfo = dbInfo, IsConnect = connectResult });//触发选择事件
            }

        }


        private void DbinfoSelectCombo_VisibleChanged(object sender, EventArgs e)
        {
          //  this.cboTreeDbInfo.RectColor = Setting.Theme.BackColor;
        }

    }

    /// <summary>
    /// 菜单操作委托参数类
    /// </summary>
    public class DbinfoEventArgs : EventArgs
    {
        /// <summary>
        /// 数据库连接对象
        /// </summary>
        public DbInfo DbInfo { get; set; }

        /// <summary>
        /// 是否连接成功
        /// </summary>
        public bool IsConnect { get; set; } = false;

    }
}
